<?php

namespace app\admin\controller\Bill;

use app\common\model\CostBill;
use app\common\model\DinnerRecord;
use Exception;
use ba\Random;
use think\facade\Db;
use app\common\controller\Backend;
use app\admin\model\User as UserModel;
use think\db\exception\PDOException;
use think\exception\ValidateException;

class Bill extends Backend
{
    protected $model = null;

    protected $withJoinTable = ['group'];

    // 排除字段
    protected $preExcludeFields = ['lastlogintime', 'loginfailure', 'password', 'salt'];

    protected $quickSearchField = ['username', 'nickname', 'id'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new UserModel();
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        foreach ($where as $k=>$v){
            if($v[0]=='user.month'){
                $between_time=$v[2];
            }
            unset($where[$k]);
        }
//        print_r($where);
//        exit();
        $res = $this->model
            ->withoutField('password,salt')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        if(!isset($between_time)){
            $between_time=[  strtotime(date('Y-m')),time()] ;
        }

        $total_cost=CostBill::whereBetween('create_time',$between_time)->sum('amount');
        $dinner_total_cost=CostBill::whereBetween('create_time',$between_time)->where(['type'=>1])->sum('amount');
        $living_total_cost=CostBill::whereBetween('create_time',$between_time)->where(['type'=>2])->sum('amount');

        $total_times=DinnerRecord::whereBetween('create_time',$between_time)->count('id');

        $dinner_per_cost=$total_times>0?bcdiv($dinner_total_cost,$total_times,2):0;


        foreach ($res as $key=>$value){
            $value['month']=$between_time[0];
            $value['my_dinner_times']=DinnerRecord::whereBetween('create_time',$between_time)->where(['user_id'=>$value['id']])->count('id');
            $value['my_dinner_spend']= bcmul($dinner_per_cost, $value['my_dinner_times'],2);
            $value['my_life_spend']=$value['group_id']>0? bcdiv($living_total_cost,3,2):0;
            $value['my_cost']=CostBill::whereBetween('create_time',$between_time)->where(['user_id'=>$value['id']])->sum('amount');
            $value['my_hand_up']= bcsub(bcadd($value['my_dinner_spend'],$value['my_life_spend'],2),$value['my_cost'],2);
        }

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $salt   = Random::build('alnum', 16);
            $passwd = encrypt_password($data['password'], $salt);

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $data['salt']     = $salt;
                $data['password'] = $passwd;
                $result           = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|Exception|PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit($id = null)
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        if ($this->request->isPost()) {
            $password = $this->request->post('password', '');
            if ($password) {
                $this->model->resetPassword($id, $password);
            }
            parent::edit();
        }

        unset($row->salt);
        $row->password = '';
        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 重写select
     */
    public function select()
    {
        $this->request->filter(['strip_tags', 'trim']);

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        foreach ($res as $re) {
            $re->nickname_text = $re->username . '(ID:' . $re->id . ')';
        }

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
}